﻿using System.IO;
using NUnit.Framework;
using WeBlog.Helpers;
using WeBlog.Models;
using WeBlog.Services;

namespace WeBlog.Tests.Services
{
	[TestFixture]
	public class SiteManagerShould
	{
		const string abcName = "ABC Blog";
		const string defName = "Blog of DEF";
		const string abcUrl = "http://www.abc.com";
		const string defUrl = "http://www.def.com:5233";

		SiteConfiguration abcConfItem;
		SiteConfiguration defConfItem;

		[SetUp]
		public void SetUp()
		{
			abcConfItem = new SiteConfiguration();
			defConfItem = new SiteConfiguration();
			
			abcConfItem.Name = abcName;
			defConfItem.Name = defName;
			abcConfItem.HostHeaderValues = abcUrl;
			defConfItem.HostHeaderValues = defUrl;
		}

		[TearDown]
		public void TearDown()
		{
			var directory = FileManager.SiteDirectory;
			if (directory.Exists)
			{
				directory.Delete(true);
			}
		}

		[Test]
		public void DetectIfNoSettingExists()
		{
			Assert.False(SiteManager.Any());
		}

		[Test]
		public void DetectIfAnySettingExists()
		{
			SiteManager.Save(abcConfItem);

			Assert.True(SiteManager.Any());

			SiteManager.Save(defConfItem);

			Assert.True(SiteManager.Any());
		}

		[Test]
		public void DetectCurrentConfigurationCompletedOrNot()
		{
			_PrepareHttpFor(abcUrl);

			Assert.False(SiteManager.IsCurrentSiteConfigured());
			
			SiteManager.Save(abcConfItem);
			
			Assert.True(SiteManager.IsCurrentSiteConfigured());
		}

		[Test]
		public void ReturnDefaultSiteConfigurationAsCurrentIfNoSettingExists()
		{
			var siteConfiguration = SiteManager.CurrentConfiguration;

			Assert.IsInstanceOf<SiteConfiguration>(siteConfiguration);
		}

		[Test]
		public void SaveSiteConfigurationAndRetreiveItByName()
		{
			SiteManager.Save(abcConfItem);
			SiteManager.Save(defConfItem);

			SiteConfiguration loadedConfItem1 = SiteManager.Load(abcName);
			SiteConfiguration loadedConfItem2 = SiteManager.Load(defName);

			Assert.AreEqual(abcConfItem, loadedConfItem1);
			Assert.AreEqual(defConfItem, loadedConfItem2);
		}

		[TestCase(abcUrl, abcName)]
		[TestCase(defUrl, defName)]
		public void ReturnProperConfigurationByUrlRequested(string baseUrl, string confName)
		{
			SiteManager.Save(abcConfItem);
			SiteManager.Save(defConfItem);
			_PrepareHttpFor(baseUrl);

			Assert.AreEqual(confName, SiteManager.CurrentConfiguration.Name);
		}

		private void _PrepareHttpFor(string baseUrl)
		{
			System.Web.HttpContext.Current = new System.Web.HttpContext(
				new System.Web.HttpRequest(null, baseUrl, null),
				new System.Web.HttpResponse(new StringWriter()));
		}
	}
}
